<!-- FileUpload.vue -->
<template>
  <div style="text-align: center">
    <el-upload
      class="upload-demo"
      :action="uploadApiUrl"
      :before-upload="beforeUpload"

      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :file-list="fileList"
      list-type="picture"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>

    <!-- <div class="image-list">
      <el-image
        style="width: 100px; height: 100px"
        v-for="(image, index) in urls"
        :key="index"
        :src="getImageUrl(image)"
        :alt="image"
        class="uploaded-image"
        :preview-src-list="urls.map((item) => getImageUrl(item))"
      >
        >
        <div slot="error" class="image-error">加载失败</div>
      </el-image>
    </div> -->
  </div>
</template>

<script>
import Axios from 'axios'
import { Message } from 'element-ui'
export default {
  props: {
    uploadApiUrl: String, // 上传接口的URL
    extraParams: Object,
    images: {
      type: Array,
      default: () => []
    }, //
    fetchData: Function,
    url: String,

    dialogVisible: false
  },
  data() {
    return {
      imageName: '', // 用于显示图片名称的输入框的值
      uploading: false, // 标志位，表示是否正在上传
      fileList: [],
      imageList: [], // 存储上传的图片信息
      urls: []
      // currentFileName:''
    }
  },
  computed: {
    // filteredImages() {
    //   console.log(
    //     "aaaaaa",
    //     this.images.filter((image) => image.dcblx === this.extraParams.dcblx)
    //   );
    //   return this.images.filter(
    //     (image) => image.dcblx === this.extraParams.dcblx
    //   );
    // },
  },
  mounted() {
    // console.log('图片路径',this.url)
    console.log('Component mounted')
    // this.urls.push(this.url.split(","))
    // this.urls.push(...this.url.split(','));
    if (this.url && this.url.trim() !== '') {
      this.urls.push(...this.url.split(','))
      this.fileList = this.url.split(',').map((filename) => ({
        name: filename,
        url: `http://49.232.236.127/wzimg/${filename}` // 替换成你的图片服务器的基础 URL
      }))
    }
    console.log('urls', this.urls)
    // 在组件加载时初始化数据
    // if (this.$route.params.id) {
    //   this.showName();
    // }
  },
  updated() {
    console.log('Component updated')
    // console.log("Component updated");
    // if (this.$route.params.id) {
    //   this.showName();
    // }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log('调用了删除')
      // console.log('....',file.name);
      // console.log(this.fileList);
      // 通过文件的 name 属性查找对应的图片数据
      const index = this.fileList.findIndex((item) => item.name === file.name)
      if (index !== -1) {
        // 从 urls 数组和 fileList 数组中删除对应的数据
        this.urls.splice(index, 1)
        this.fileList.splice(index, 1)

        // 发送删除事件给父组件
        this.$emit('delete-image', {
          dcblx: this.extraParams.dcblx,
          fileName: file.name
        })

        console.log(`图片 ${file.name} 删除成功`)
      } else {
        console.error(`未找到要删除的图片 ${file.name}`)
      }
    },

    beforeUpload(file) {
      console.log('before-upload called')
      // 如果正在上传，则直接返回
      if (this.uploading) {
        return false
      }
      // 保存文件名字到临时变量
      // this.currentFileName = file.name || file.raw.name;
      // 创建 FormData 对象
      const formData = new FormData()

      // 添加文件
      formData.append('file', file)

      // 添加额外的参数
      if (this.extraParams) {
        // console.log(999999999999, this.extraParams);

        for (const key in this.extraParams) {
          if (Object.hasOwnProperty.call(this.extraParams, key)) {
            formData.append(key, this.extraParams[key])
          }
        }
        // console.log(555555555, this.extraParams);
      }
      // 设置上传标志位
      this.uploading = true
      // 发送 Fom,rmData 到后端
      // console.log("formData1", formData);
      this.uploadFile(formData)

      // return isJPG && isLt500k;
      // return false;
      return true
    },
    uploadFile(formData) {
      console.log('uploadFile called')
      console.log('formData', formData)
      // 使用你的方式发送 FormData 到后端
      // 例如使用 axios 或者 Vue Resource
      Axios.post(this.uploadApiUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then((response) => {
          console.log('ddddddd', response)
          // console.log(444444444);
          if (response.data.code == -1) {
            console.log(2222)
            Message({
              message: '图片可能重复',
              type: 'error',
              duration: 3000
            })
            return
          }
          this.handleSuccess(response.data)
        })
        .catch((error) => {
          this.handleError(error)
        })
        .finally(() => {
          // 重置上传标志位
          this.uploading = false
        })
    },
    handleSuccess(response) {
      // console.log("555555", file);
      // 文件上传成功后的处理逻辑
      console.log('上传图片成功后的数据', response)

      //  我想将这个response.data.newFileName放到this.formData中对应的zpbh中
      console.log('图片名字', response.data.oldFileName)
      console.log('图片名字', response.data.newFileName)
      console.log('extraParams', this.extraParams)
      console.log('文件上传成功:', response)

      // this.urls.push(response.data.newFileName);

      this.fileList.push({
        name: response.data.newFileName,
        url: `http://49.232.236.127/wzimg/${response.data.newFileName}` // 假设服务器返回的数据中有图片的url
      })
      this.$emit('upload-success', {
        dcblx: this.extraParams.dcblx,
        fileName: response.data.newFileName
      })
      Message({
        message: '图片上传成功',
        type: 'info',
        duration: 3000
      })
    },
    async showName() {
      // console.log("执行");
      try {
        // console.log('aaaaaaaaa');
        const imageList1 = await this.$api.fetchImagesBySampleId(
          this.$route.params.id
        )

        // console.log('测试imageList1',imageList1);
        const list = imageList1.data.data.filter(
          (image) => image.dcblx === this.extraParams.dcblx
        )
        console.log('测试list', this.extraParams.dcblx, list)
        const filenames = list.map((item) => item.filename)

        const joinedFilenames = filenames.join('; ')

        this.imageName = joinedFilenames
      } catch (error) {
        console.error('Error fetching images:', error)
      }
    },
    handleError(error) {
      // 文件上传失败的处理逻辑
      console.error('文件上传失败:', error)
      Message({
        message: '图片上传失败',
        type: 'error',
        duration: 3000
      })
    },

    getImageUrl(hashfile) {
      console.log('我人麻了', hashfile, this.urls)
      // 这里假设图片的路径是相对路径
      // 实际情况可能需要根据你的后端返回的数据进行调整
      // this.imageName = hashfile;
      return `http://49.232.236.127/wzimg/${hashfile}`
    }
  }
}
</script>

<style>
.el-input.is-disabled .el-input__inner {
  background-color: white;
}

.upload-demo {
  margin-bottom: 20px;
}

.image-list {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
}

.uploaded-image {
  position: relative;
  margin-right: 10px;
  cursor: pointer;
}

.image-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
}

.el-upload-list__item {
  width: 25%;
  float: left;
}
</style>
